<script setup>
import MwTable from "./component/MwTableAccount";
import SearchTable from "./component/SearchAccount.vue"
import MwDialog from "@/components/Dialog"
import { ElMessage, ElMessageBox } from 'element-plus'
import { globalStore } from "@/store/global";
const globalVue = globalStore();
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue"

const instance = getCurrentInstance()
const _this = instance.appContext.config.globalProperties //vue3获取当前this

// 生命周期
onMounted(() => {
  getTableData()
  getSelect();
})

let getTableData = () => {
  // 查询
  let paramsVehicle = {
    ...pagination,
    ...searchForm
  }
  instance.proxy.$http.get('user.getUserList',{ params: paramsVehicle }).then(res=>{
    let {content, totalElements} = res.data;
    tableData.value = content;
    pagination.total = totalElements;
  })
}

let getSelect = async () => {
  selectRole.value = await globalVue.getSelect('roleSelect');
  instance.proxy.$http.get('archiveData.getAmbulanceTreeSelect').then(res => {
    treeOrganizationSelect.value = formatTree(res.data, 1)
  });
}
// 下拉数据
const selectRole = ref([]);   // Role
const treeOrganizationSelect = ref([]);


function formatTree(treeData, zoom) {
  let treeArr = []
  treeData.forEach(i => {
    let item = {}
    item.label = i.name;
    item.zoom = zoom;
    item.value = i.id || i.type;
    if (i.city) {
      item.city = i.city
      item.type = i.type
    }
    i.list && (item.children = formatTree(i.list, zoom + 1))
    if (item.children && item.children.length) {
      item.disabled = false;
    }else{
      item.disabled = item.zoom != 2;
    }
    item.zoom < 3 && treeArr.push(item)
  })
  return treeArr
}

// 弹框数据
let dialogShow = ref(false);
let dialogTitle = ref(' User');
let dialogState = ref('Add'); //  Add Edit Detail 三种状态 根据状态来判断提交方法
let dialogRef = ref(null);
let dialogFrom = reactive({})
let dialogRules = reactive({
  userId: [
    { required: true, message: 'Please input userID', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'Characters cannot have spaces before or after them', trigger: 'blur' }, 
  ],
  username: [
    { required: true, message: 'Please input userName', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'Characters cannot have spaces before or after them', trigger: 'blur' }, 
  ],
  role: [
    { required: true, message: 'Please input role', trigger: 'blur' },
  ],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' },
  ],
})
let dialogSubmit = async () => {
  let formEl = dialogRef.value;
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogFrom?.hospitalIdLists && delete dialogFrom?.hospitalIdLists;
      delete dialogFrom?.organizationIdList;
      
      let url = dialogState.value == 'Add' ? 'user.addUser' : 'user.updateUser';
      if (dialogState.value == 'Add') {
        instance.proxy.$http.post(url, dialogFrom).then(res=>{
          onSearch()
        })
      }else{
        instance.proxy.$http.put(url, dialogFrom).then(res=>{
          onSearch()
        })
      }
      dialogClose();
    } else {
      console.err('error submit!', fields)
    }
  })
}

let dialogClose = () => {
  dialogShow.value = false;
  dialogFrom
  for(let item in dialogFrom){
    if(dialogFrom[item] instanceof Array){
      dialogFrom[item] = [];
    }else{
      dialogFrom[item] = ''
    }
  }
}

function openDialog(state) {
  tabsActive.value = 'user'
  dialogState.value = state
  dialogShow.value = true;
  for(let item in dialogFrom){
    if(dialogFrom[item] instanceof Array){
      dialogFrom[item] = [];
    }else{
      dialogFrom[item] = ''
    }
  }
}

// 表格数据
let tableData = ref([])
let pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})
let searchForm = reactive({})
function onSearch(){
  getTableData()
}

function onEdit(row){
  openDialog('Detail')
  for(let i in row) {
    if (i == 'hospitalIdList') {
      dialogFrom[i] = row[i]
      dialogFrom['hospitalIdLists'] = formatAmbulanceId(treeOrganizationSelect.value, row[i])
    }else{
      dialogFrom[i] = row[i];
    }
  }
}
function formatAmbulanceId(treeData, idList) {
  let arr = [];
  treeData.forEach(i => {
    i.children.forEach(x => {
      idList?.forEach(c => {
        if (x.value == c.id) {
          arr.push([i.value, x.value])
        }
      })
    })
  })
  return arr
}

function resetPassword(row){
  ElMessageBox.confirm(
    'Do you want to reset the password ？',
    'Reset Password',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.get('user.resetPassword', {params: {id: row.id + ''}, tipConfig: {hideMsg: true}}).then(res=>{})
    })
    .catch(() => {})
}

function onDelete(row){
  ElMessageBox.confirm(
    'Do you want to delete the current contact？',
    'Delete People',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.delete('user.deleteUser', {data: {id: row.id + ''}}).then(res=>{
        onSearch();
        ElMessage({
          type: 'success',
          message: 'Delete User successfully',
        })
      })
    })
    .catch(() => {})
}

function changeStatus(row, column){
  instance.proxy.$http.put('user.updateUser', {id: row.id, status: row.status}).then(res=>{
    ElMessage({
      type: 'success',
      message: 'Status updated',
    })
  })
}


const tabsActive = ref('user');
const cascaderProps = {multiple: true}
const cascaderValue = ref([])

function cascaderChange(val) {
  dialogFrom.hospitalIdList = val.map(i => {
    return {id: i.at(-1)}
  })
}

</script>
<template>
  <div class="table_index">
    <SearchTable :searchForm="searchForm" @search="onSearch" @addUser="openDialog('Add')" />
    <div class="table_content">
      <mw-table
        :data="tableData"
        :pagination="pagination"
        @paginationChange="onSearch"
        @operate1="onEdit"
        @operate2="resetPassword"
        @operate3="onDelete"
        @changeStatus="changeStatus"
      ></mw-table>
    </div>
  </div>
  <mw-dialog
    :show="dialogShow"
    width="800px"
    :title="dialogState + dialogTitle"
    @submit="dialogSubmit"
    @close="dialogClose"
  >
    <el-form ref="dialogRef" :model="dialogFrom" label-position="top" :rules="dialogRules">
      <el-form-item label="UserID" prop="userId">
        <el-input v-model="dialogFrom.userId" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Username(Loginname)" prop="username">
        <el-input v-model="dialogFrom.username" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Password" prop="password">
        <el-input v-model="dialogFrom.password" type="password" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Nickname">
        <el-input v-model="dialogFrom.nickname" placeholder="Enter" clearable />
      </el-form-item>
      <div style="display: flex;">
        <el-form-item style="width: 50%" label="Role" prop="role">
          <el-select
            v-model="dialogFrom.role"
            placeholder="Please select"
            clearable
          >
            <el-option v-for="item in selectRole" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 50%" label="Organization" prop="organ">
          <el-cascader 
            style="width: 100%;"
            clearable 
            collapse-tags
            v-model="dialogFrom.hospitalIdLists"
            collapse-tags-tooltip
            max-collapse-tags="3"
            :props="cascaderProps"
            :show-all-levels="false"
            :options="treeOrganizationSelect" 
            @change="cascaderChange" />
        </el-form-item>
      </div>
      <el-form-item label="Telephone">
        <el-input v-model="dialogFrom.phone" placeholder="Enter" clearable />
      </el-form-item>
    </el-form>
  </mw-dialog>
</template>